<template>
	<view>
		<commonLine></commonLine>
		<view class="search-item">
			<view class="search-title">
				<view class="f-color">最近搜索</view>
				<view @tap="emptyArr" class="iconfont icon-iconset0213"></view>
			</view>
			<view class="f-color" v-if="keyWords.length!==0">
				<block v-for="item in keyWords" :key="item">
					<view class="search-name" @tap="search(item)">{{item}}</view>
				</block>
			</view>
			<view class="f-color" v-if="keyWords.length===0">
				<view class="no-keyword">
					暂无搜索历史
				</view>
			</view>
		</view>
		<view class="search-item">
			<view class="f-color">热门搜索</view>
			<view class="iconfont icon-lajitong"></view>
			<view class="f-color">
				<view class="search-name">四件套</view>
				<view class="search-name">面膜</view>
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		ref
	} from "vue";
	import {
		onLoad,
		onNavigationBarButtonTap,
		onNavigationBarSearchInputChanged,
		onNavigationBarSearchInputConfirmed
	} from '@dcloudio/uni-app';
	let text = ref('');

	let keyWords = ref([]);

	const search = (keyword) => {
		if (keyword === '') {
			uni.showToast({
				title: "请输入关键词",
				icon: "none"
			})

			setTimeout(() => {
				uni.hideToast();
			}, 1000);

			return;
		}

		// 查询最大长度不能超过9，并且去重
		const index = keyWords.value.indexOf(keyword);
		if (keyWords.value.length > 8) {
			if (index !== -1) {
				keyWords.value.splice(0, 1, keyword);
			} else {
				keyWords.value.splice(index, 1);
				keyWords.value.splice(0, 0, keyword);
			}
		} else {
			if (index !== -1) {
				keyWords.value.splice(index, 1);
				keyWords.value.splice(0, 0, keyword);
			} else {
				keyWords.value.unshift(keyword);
			}
		}
		uni.setStorageSync('keyWords', keyWords.value);
		uni.navigateTo({
			url: "../searchList/searchList?text=" + keyword
		});
	}

	const emptyArr = () => {
		uni.showModal({
			title: "提示",
			content: "确定要清空记录吗？",
			cancelText: "取消",
			confirmText: "确定",
			success: (e) => {
				if (e.confirm) {
					keyWords.value.length = 0;
					uni.removeStorageSync('keyWords');
				}
			}
		})
	}

	onLoad(() => {
		uni.setStorageSync('keyWords', keyWords);

		keyWords.value = uni.getStorageSync('keyWords')._rawValue;
	})
	// 监听右上角搜索
	onNavigationBarButtonTap((e) => {
		search(text.value);
	});
	// 监听软键盘搜索
	onNavigationBarSearchInputConfirmed(() => {
		search(text.value);
	})
	// 监听输入change
	onNavigationBarSearchInputChanged((e) => {
		text.value = e.text;
	})
</script>

<style lang="scss" scoped>
	.uni-page-head {
		padding: 0 !important;
	}

	.search-item {
		padding: 20rpx;

		.search-title {
			display: flex;
			justify-content: space-between;
		}

		.search-name {
			padding: 4rpx 24rpx;
			background-color: #e1e1ee;
			display: inline-block;
			border-radius: 26rpx;
			margin: 10rpx;
			max-width: 100rpx;
			overflow: hidden;
			white-space: nowrap;
			text-overflow: ellipsis;
		}

		.no-keyword {
			text-align: center;
			font-size: 32rpx;
		}
	}
</style>
